package Recommendation;

import User.User;

public class Pearson implements Recommendation
{
	private User user1;
	private User user2;
	
	public Pearson(User user1, User user2)
	{
		this.user1 = user1;
		this.user2 = user2;
	}
	
	public double calc()
	{
		double[] ratings1 = user1.getRatings(user1.getSharedIds(user2));
		double[] ratings2 = user2.getRatings(user1.getSharedIds(user2));
		double average1 = sum(ratings1) / ratings1.length;
		double average2 = sum(ratings2) / ratings2.length;
		
		double totalRating = 0;
		for (int id : user1.getSharedIds(user2))
		{
			totalRating += (user1.getRating(id) - average1) * (user2.getRating(id) - average2);
		}
		
		double root1 = 0;
		double root2 = 0;
		for (int id : user1.getSharedIds(user2))
		{
			root1 += Math.pow(user1.getRating(id) - average1, 2);
			root2 += Math.pow(user2.getRating(id) - average2, 2);
		}
		root1 = Math.sqrt(root1);
		root2 = Math.sqrt(root2);
		
		if (root1 * root2 == 0)
		{
			return 0;
		}
		
		return Math.max(Math.min(totalRating / (root1 * root2), 1), -1);
	}
	
	private double sum(double[] list)
	{
		double result = 0;
		for (double i : list)
		{
			result += i;
		}
		
		return result;
	}
}
